const Index = require('./index')
const config  = require('../../static/config')
const Notify = require('../../static/vant/notify/notify').default

let request

export function init() {
  console.d('init api')
  try {
    request = Index.initRequest()
    request.handleServerErr = function(e) {
      // wx.hideLoading()
      console.log('handleServerErr', e)
      let app = getApp()
      app.setToastLock(false)
      if (e && e.response) {
        app.showError('服务器失败')
        // app.showError(e.response.data, 100000)
        // app.showDebug(e.status, e.response.data)
      }
    }
    request.handleErrCode = function(code) {
      if (code > 20000) {
        let app = getApp()
        console.error(  'handleErrCode', code)
        if (code == 50012) {
          // access_token 过期
          // 过期才可以重新请求
          app.requestToken()
        }
        if (code == 50015) {
          // access_token 不合法
          app.checkIsRegistered()
        }
      }
      return true
    }
    request.shouldCatchErr = function(res) {
      if (res && res.request) {
        console.d('shouldCatchErr', res, res.request.url)
        if (res.request.url.indexOf('student/register') > -1) {
          if (!res || !res.data || !res.data.code ) {
            return true
          } else {
            return res.data.code > 20000 && res.data.code !== 61003
          }
        } else {
          return !res || !res.data || !res.data.code || res.data.code > 20000
        }
      } else {
        return true
      }
    }

    request.handleErrMessage = function (message, err, res, config, context) {
      let app = getApp()
      if (res) {
        let request = res.request
        let pages = getCurrentPages()
        let lastPage = null
        if (pages && pages.length > 0) {
          lastPage = pages[pages.length - 1]
        }
        let allowGo = true
        console.d('handleErrMessage', request)
        if (lastPage && lastPage.handleErrMessage) {
          allowGo = lastPage.handleErrMessage(message, err, res, config, {
            Notify,
            request,
            context
          })
        }

        if (!allowGo) {
          return
        }

        setTimeout(() => {
          context.hideLoadingUI()
        }, 1000)
        app.setToastLock(false)
        if (config.mode === 'dev' && !config.forceToast) {
          app.showDevError(message)
        } else {
          app.showError(message)
        }
      } else {
        console.error('no res', message, err)
      }
    }

  } catch (e) {
    console.error('api failed', e)
  }
}

function formatUrl(url, args = {}, h = (v) => { return v + '/' }) {
  return Index.formatUrl.apply(Index, [h(url), args])
}

function nativePost(url, data, header, options = {}) {
  wx.request({
    url,
    method: 'POST',
    data: data,
    header: header,
    success(res) {
      if (options.success) {
        options.success(res)
      }
    },
    fail(e) {
      if (options.fail) {
        options.fail(e)
      }
    }
  })
}

// {
//   "uid": "oCVfUw7A9Hacj3zmMsLzJI2Vtd50",
//   "provider": "weixin",
//   "extra_data": "{}"
// }
/**
 * 检测学生是否已经注册
 *
 * @param uid
 * @param extraData
 * @param params
 * @returns {*}
 */
export function checkStudentNeedRegister(uid, extraData = {}) {
  return new Promise((resolve, reject) => {
    nativePost(
      formatUrl(config.request.base + '/check/student/registered'),
      {
        uid,
        "provider": "weixin",
        "extra_data": JSON.stringify(extraData),
      },
      {
        'auth-sys': 'student'
      },
      {
        success(res) {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.statusCode + ' ' + res.data))
          }
        },
        fail(e) {
          reject(e)
        }
      }
    )
  })
}

/**
 * 发送短信验证码
 *
 * @param action  ((1, "signup"), (2, "reset"), (3, "binding"))
 * @param mobile
 * @param params
 * @returns {*}
 */
export function sendSMSCode(mobile, action, params = {}) {
  return request.get(
    formatUrl(config.request.base + '/user/validate'),
    {
      action,
      mobile,
      ...params
    }
  )
}

/**
 * 我的课程列表
 *
 * @param params
 * @returns {*}
 */
export function getStudentCourse(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/course'),
    params
  )
}

/**
 * 获取学员登录token
 *
 * @param extraData
 *
 {
	"uid": "636363",
	"provider": "weixin",
	"extra_data": "{}"
 }
 * @returns {*}
 */
export function commonTokenCreate(uid, extraData = {}, appendData = {}) {
  // let request = Index.initRequest()
  // request.needHandleErr = false
  // return request.post(
  //   formatUrl(config.request.base + '/common/token/create'),
  //   {
  //     uid,
  //     "provider": "weixin",
  //     extra_data: JSON.stringify(extraData)
  //   }
  // )
  return new Promise((resolve, reject) => {
    wx.request({
      method: 'POST',
      url: formatUrl(config.request.base + '/common/token/create'),
      header: {
        ['auth-sys']: 'student'
      },
      data: {
        uid,
        "provider": "weixin",
        extra_data: JSON.stringify(extraData),
        ...appendData
      },
      success(e) {
        if (!e.data) {
          reject(new Error('oh'))
        }
        resolve(e.data)
      },
      fail(e) {
        reject(e)
      }
    })
  })
}

/**
 * 学员注册
 *
 * @param data
 * @param extraData
 * @param type
 * @param query
 * @returns {*}
 */
export function registerStudent(data = {}, extraData = {}, type = 0, query = '') {
  return request.post(
    formatUrl(config.request.base + `/student/register`) + `?type=${type}` + query,
    {
      ...data,
      "provider": "weixin",
      extra_data: JSON.stringify(extraData)
    }
  )
}

/**
 * 我的课程列表
 *
 * @param uuid 课程uuid
 * @param params
 * @returns {*}
 */
export function getStudentCourseProgress(uuid, params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/course/:uuid/progress', {
      uuid
    }),
    params
  )
}

/**
 * 查看学员信息
 *
 * @param params
 * @returns {*}
 */
export function getStudentProfile(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/profile'),
    params
  )
}

/**
 * 编辑学员信息
 *
 * @param data
 * @returns {*}
 */
export function editStudentProfile(data = {}) {
  return request.put(
    formatUrl(config.request.base + '/student/profile'),
    data
  )
}

/**
 * 查看学员收货地址
 *
 * @param params
 * @returns {*}
 */
export function getStudentAddress(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/address'),
    params
  )
}

/**
 * 新增学员收货地址
 *
 * @param data
 * @returns {*}
 */
export function addStudentAddress(data = {}) {
  return request.post(
    formatUrl(config.request.base + '/student/address'),
    data
  )
}

/**
 * 查看学员收货地址详情
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentAddressDetail(uuid, params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/address/:uuid', {
      uuid
    }),
    params
  )
}

/**
 * 编辑学员收货地址
 *
 * @param uuid
 * @param data
 * @returns {*}
 */
export function editStudentAddress(uuid, data = {}) {
  return request.put(
    formatUrl(config.request.base + '/student/address/:uuid', {
      uuid
    }),
    data
  )
}

/**
 * 删除学员收货地址
 *
 * @param uuid
 * @param data
 * @returns {*}
 */
export function deleteStudentAddress(uuid, data = {}) {
  return request.delete(
    formatUrl(config.request.base + '/student/address/:uuid', {
      uuid
    }),
    data
  )
}

/**
 * 查看学员报考信息
 *
 * @param params
 * @returns {*}
 */
export function getRegistration(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/registration', {
    }),
    params
  )
}

export function getStudentCourseIntentionCheck(uuid, params = {}) {
  return request.get(
    formatUrl(config.request.base + `/student/course/:uuid/intention/check`, {
      uuid
    }),
    params
  )
}

export function getStudentCourseConfirmationCheck(uuid, params = {}) {
  return request.get(
    formatUrl(config.request.base + `/student/course/:uuid/confirmation/check`, {
      uuid
    }),
    params
  )
}

/**
 * 验证学员身份
 *
 * @param data
 * @returns {*}
 */
export function checkStudentIdentity(data = {}) {
  return request.post(
    formatUrl(config.request.base + '/check/student/identity', {
    }),
    data
  )
}

/**
 * 查询公共课授课计划
 *
 * @param subject_id
 * @param course_id
 * @param params
 * @returns {*}
 */
export function getStudentLessonplanCommon(subject_id, course_id, params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/lessonplan/common', {
    }),
    {
      subject_id,
      course_id,
      ...params
    },
  )
}

/**
 * 查询专业课授课计划
 *
 * @param subject_id
 * @param course_id
 * @param params
 * @returns {*}
 */
export function getStudentLessonplanMajor(course_id, params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/lessonplan/major', {
    }),
    {
      course_id,
      ...params
    },
  )
}

/**
 * 查看学员课节列表
 *
 * @param chapter_id
 * @param params
 * @returns {*}
 */
export function getStudentSection(chapter_id, params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/section', {
    }),
    {
      chapter_id,
      ...params
    }
  )
}

/**
 * 查看学员课节详情
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentSectionDetail(uuid, params = {}) {
  return request.get(
    formatUrl(config.request.base + '/student/classhour/:uuid', {
      uuid
    }),
    params
  )
}

/**
 * 学员确认课时
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function agreeStudentClasshour(uuid, params = {}) {
  return request.put(
    formatUrl(config.request.base + '/student/classhour/agree/:uuid', {
      uuid
    }),
    params
  )
}

/**
 * 学员驳回课时
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function rejectStudentClasshour(uuid, params = {}) {
  return request.put(
    formatUrl(config.request.base + '/student/classhour/reject/:uuid', {
      uuid
    }),
    params
  )
}

/**
 * 地区列表 (分级返回)
 *
 * @param params
 * @returns {*}
 */
export function getArea(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/area'),
    params
  )
}

/**
 * 获取省市关联列表
 *
 * @param params
 * @returns {*}
 */
export function getPovinceCitys(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/province/city'),
    params
  )
}

/**
 * 院校列表
 *
 * @param params
 * @returns {*}
 */
export function getSchool(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/school'),
    params
  )
}

/**
 * 所有专业列表 (分级返回)
 *
 * @param params
 * @returns {*}
 */
export function getMajor(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/major'),
    params
  )
}


/**
 * 院校的院系列表
 *
 * @param params
 * @returns {*}
 */
export function getSchoolDepartment(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/school/department'),
    params
  )
}

/**
 * 院系的专业列表
 *
 * @param params
 * @returns {*}
 */
export function getDepartmentMajor(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/department/major'),
    params
  )
}

/**
 * 院系的院系与专业 (关联)
 *
 * @param params
 * @returns {*}
 */
export function getSchoolDepartmentMajor(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/school/department/major'),
    params
  )
}

/**
 * 专业需靠的业务课
 *
 * @param params
 * @returns {*}
 */
export function getMajorExamSubject(params = {}) {
  return request.get(
    formatUrl(config.request.base + '/major/exam/subject'),
    params
  )
}

/**
 * 课程服务状态
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentCourseStatus(uuid, params) {
  return request.get(
    formatUrl(config.request.base + '/student/course/:uuid/status', {
      uuid,
    }),
    params,
  )
}

/**
 * 意向表提交状态
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentCourseIntentionStatus(uuid, params) {
  return request.get(
    formatUrl(config.request.base + '/student/course/:uuid/intention/status', {
      uuid,
    }),
    params,
  )
}

/**
 * 提交意向表
 *
 * @param uuid 课程uuid
 * @param data
 * @returns {*}
 */
export function addStudentCourseIntention(uuid, data) {
  return request.post(
    formatUrl(config.request.base + '/student/course/:uuid/intention', {
      uuid,
    }),
    data,
  )
}

/**
 * 编辑意向表
 *
 * @param course_uuid 课程uuid
 * @param data
 * @returns {*}
 */
export function editStudentCourseIntention(course_uuid, data) {
  return request.put(
    formatUrl(config.request.base + '/student/course/:course_uuid/intention', {
      course_uuid,
    }),
    data,
  )
}

/**
 * 查看意向表
 *
 * @param params
 * @param uuid
 * @returns {*}
 */
export function getStudentCourseIntentionDetail(uuid, params) {
  return request.get(
    formatUrl(config.request.base + '/student/course/:uuid/intention', {
      uuid,
    }),
    params
  )
}

/**
 * 评价意向表
 *
 * @param uuid
 * @param data
 * @returns {*}
 */
export function addStudentIntentionEvaluation(uuid, data) {
  return request.post(
    formatUrl(config.request.base + '/student/intention/:uuid/evaluation', {
      uuid,
    }),
    data,
  )
}

/**
 * 查看意向单评价
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentIntentionEvaluation(uuid, params) {
  return request.get(
    formatUrl(config.request.base + '/student/intention/:uuid/evaluation', {
      uuid,
    }),
    params,
  )
}

/**
 * 查看确认状态单
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentCourseConfirmationStatus(uuid, params = {}) {
  return request.get(
    formatUrl(config.request.base + `/student/course/:uuid/confirmation/status`, {
      uuid,
    }),
    params,
  )
}

/**
 * 提交确认单
 *
 * @param uuid
 * @param data
 * @returns {*}
 */
export function addStudentCourseConfirmation(uuid, data) {
  return request.post(
    formatUrl(config.request.base + '/student/course/:uuid/confirmation', {
      uuid,
    }),
    data,
  )
}

/**
 * 编辑确认单
 *
 * @param uuid
 * @param data
 * @returns {*}
 */
export function editStudentCourseConfirmation(uuid, data) {
  return request.put(
    formatUrl(config.request.base + '/student/course/:uuid/confirmation', {
      uuid,
    }),
    data,
  )
}

/**
 * 查看确认单
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentCourseConfirmationDetail(uuid, params) {
  return request.get(
    formatUrl(config.request.base + '/student/course/:uuid/confirmation', {
      uuid,
    }),
    params,
  )
}

/**
 * 我的老师列表
 *
 * @param uuid
 * @param params
 * @returns {*}
 */
export function getStudentTeacher(uuid, params) {
  return request.get(
    formatUrl(config.request.base + '/student/course/:uuid/teacher', {
      uuid
    }),
    params,
  )
}

/**
 * 获取考试科目
 *
 * @param params
 * @returns {*}
 */
export function getCommonExamSubject(params) {
  return request.get(
    formatUrl(config.request.base + '/common/exam/subject', {}),
    params
  )
}

/**
 * 查看考试成绩
 *
 * @param params
 * @returns {*}
 */
export function getStudentScore(params) {
  return request.get(
    formatUrl(config.request.base + '/score', {}),
    params
  )
}

/**
 * 编辑考试成绩
 *
 * @param params
 * @returns {*}
 */
export function editStudentScore(data) {
  return request.put(
    formatUrl(config.request.base + '/score', {}),
    data
  )
}

/**
 * 查询课程包含的科目列表
 *
 * @param course_id
 * @param params
 * @returns {*}
 */
export function getCommonCourseSubject(course_id, params) {
  return request.get(
    formatUrl(config.request.base + '/common/course/:uuid/subject', {
      uuid: course_id
    }),
    params,
  )
}

/**
 * 查看所有学校 (select-school-index 用)
 *
 * @param name
 * @param params
 * @returns {*}
 */
export function getSchools(name, params) {
  let searchOpt = {}
  searchOpt.name = name
  return request.get(
    formatUrl(config.request.base + '/school'),
    {
      ...searchOpt,
      ...params
    }
  )
}

/**
 * 查看专业 (select-major-index 用)
 *
 * @param name
 * @param params
 * @returns {*}
 */
export function getMajors(name, params) {
  let searchOpt = {}
  searchOpt.name = name
  return request.get(
    formatUrl(config.request.base + '/major'),
    {
      ...searchOpt,
      ...params
    }
  )
}

/**
 * 查看专业 (select-major-index 用)
 *
 * @param name
 * @param params
 * @returns {*}
 */
export function getSecondMajors(name, params) {
  let searchOpt = {}
  searchOpt.name = name
  return request.get(
    formatUrl(config.request.base + '/second/major'),
    {
      ...searchOpt,
      ...params
    }
  )
}
